'use strict';

angular.module('memoriesApp')
.controller('SettingsCtrl', function($scope, $timeout, global, toastService, dataStoreFactory) {

  var settingStore = dataStoreFactory.get('settings', true);
  var defaultSettings = global.settings;

  function init() {
    $scope.vm = {
      settings: defaultSettings
    };
    refreshSettings(watchSave);
  }

  function watchSave() {
    $scope.$watch('vm.settings', function(newVal, oldVal) {
      if (!_.isEqual(newVal, oldVal)) {
        saveSettings();
      }
    }, true);
  }

  function refreshSettings(callback) {
    settingStore.getItem(function(err, item) {
      if (err) {
        item = defaultSettings;
      }
      if (item) {
        $timeout(function() {
          $scope.vm.settings = _.defaults(item, defaultSettings);
          callback && callback();
        });
      }
    });
  }

  function saveSettings() {
    var settings = $scope.vm.settings;
    settingStore.updateItem(settings, function(err) {
      toastService.openToast({
        message: 'Settings saved!'
      });
    });
  }

  init();

});